<script setup lang="ts">
import Taro, { getCurrentInstance, showToast, showLoading, hideLoading, navigateBack } from '@tarojs/taro';
import { reactive, ref, onMounted } from 'vue';
import { useAddrStore, useAuthStore } from '@/store';
import { useNurseUser, use_hospital_dept_bed } from '@/service';
import { useGetAuthInfo } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';

const {
    router: {
        params: { id }
    }
}: any = getCurrentInstance();

// definePageConfig({
//     navigationBarTitleText: id ? '设置地址' : '新增地址'
// });

Taro.setNavigationBarTitle({
    title: id ? '编辑地址' : '新增地址'
});

// 居家护理地址不需要医院相关接口

// const { getLocation } = useweChat_location_service()

const { addHomeAddr, editHomeAddr, getHomeAddr } = useNurseUser();

const authStore = useAuthStore();
const { nurseUser } = storeToRefs(authStore);

const { getProvince, getCity, getCountry } = useAddrStore();

const formData = ref<any>({
    name: '',
    phone: '',
    area: '',
    areaName: '',
    address: '',
    isDefault: false,
    userId: nurseUser.value.id,
    id: id || '',
    longitude: '',
    latitude: ''
});

// 如果是编辑模式，获取地址详情
onMounted(async () => {
    if (id) {
        await loadAddressData();
    }
});

// 加载地址数据
async function loadAddressData() {
    if (!id) return;
    
    showLoading({ title: '加载中...' });
    try {
        const { error, success } = await getHomeAddr(id);
        console.log('success id ===', success);
        if (!error && success) {
            formData.value = { ...success };
        }
    } catch (err) {
        console.error('加载地址数据失败:', err);
    } finally {
        hideLoading();
    }
}

const ruleForm = ref<any>(null);

const select = reactive({ text: '', value: '' });

const defaultChange = () => {
    // 如果设置为默认地址，需要处理其他地址的默认状态
    // 这里可以在提交时处理，或者通过接口来处理
};

const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    showLoading({ title: '正在保存...' });
    
    try {
        let result;
        if (id) {
            // 编辑模式
            result = await editHomeAddr(formData.value);
        } else {
            // 新增模式
            result = await addHomeAddr({
                ...formData.value,
                userId: nurseUser.value.id
            });
        }

        if (!result.error) {
            showToast({
                title: '保存成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });
            
            // 刷新用户信息
            setTimeout(async () => {
                await useGetAuthInfo();
                navigateBack();
            }, 1200);
        }
    } catch (err) {
        console.error('保存地址失败:', err);
        showToast({
            title: '保存失败',
            icon: 'error',
            duration: SUCCESS_MSG_DURATION
        });
    } finally {
        hideLoading();
    }
};

const areaModule: any = reactive({
    show: false,
    province: getProvince,
    city: [{}],
    country: [{}],
    town: [],
    showArea: () => {
        areaModule.show = !areaModule.show;
        if (areaModule.show) {
            select.text = '';
            select.value = '';
        }
    },
    onChange: (item: any) => {
        const { custom, next, value } = item;

        switch (custom) {
            case 'province':
                const city = getCity.filter(item => item.pid == value.id);
                areaModule.city = city;
                break;
            case 'city':
                const country = getCountry.filter(item => item.pid == value.id);
                areaModule.country = country;
                break;
            default:
                break;
        }
        select.text += value.name;
        select.value += `${value.id}-`;
        const name = areaModule[next];
        if (!name?.length) {
            areaModule.show = false;
            formData.value.areaName = select.text;
            formData.value.area = select.value;
        }
    }
});

// 打开地图选择位置的辅助函数
const getLocation = (): Promise<{ latitude: number; longitude: number }> => {
    return new Promise((resolve) => {
        Taro.getLocation({
            type: 'wgs84',
            success(res) {
                resolve({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
            },
            fail() {
                // 如果获取失败，返回北京的默认坐标
                resolve({
                    latitude: 39.9,
                    longitude: 116.4
                });
            }
        });
    });
};

// 打开地图选择位置
const chooseLocation = async () => {
    try {
        const { latitude, longitude } = await getLocation();
        const reschooseLocation = await Taro.chooseLocation({
            latitude,
            longitude
        });
        
        formData.value.areaName = reschooseLocation.address;
        formData.value.area = reschooseLocation.address;
        formData.value.longitude = reschooseLocation.longitude;
        formData.value.latitude = reschooseLocation.latitude;
    } catch (err) {
        console.log('选择位置失败：', err);
        formData.value.areaName = '';
        formData.value.area = '';
    }
};
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="id ? '设置地址' : '新增地址'" show-left /> -->
        <view class="w-375px flex-col-center">
            <view class="w-360px">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData">
                    <nut-form-item label="联系人" prop="name" required :rules="[{ required: true, message: '请填写联系人' }]">
                        <nut-input v-model="formData.name" placeholder="请输入联系人" type="text" />
                    </nut-form-item>
                    <nut-form-item label="联系电话" prop="phone" required :rules="[{ required: true, message: '请填写联系电话' }]">
                        <nut-input v-model="formData.phone" placeholder="请输入联系电话" type="text" />
                    </nut-form-item>
                    <nut-form-item label="地区" prop="area" required :rules="[{ required: true, message: '请选择地区' }]">
                        <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" type="text"
                            @click="chooseLocation()" />
                    </nut-form-item>
                    <nut-form-item label="详细地址" prop="address" required
                        :rules="[{ required: true, message: '请填写详细地址' }]">
                        <nut-input v-model="formData.address" placeholder="请输入详细地址" type="text" />
                    </nut-form-item>
                    <nut-form-item label="默认地址" prop="isDefault">
                        <nut-switch v-model="formData.isDefault" @change="defaultChange"></nut-switch>
                    </nut-form-item>
                    <nut-cell>
                        <basic-button text="保存" class="mt-2" @on-click="submit" />
                    </nut-cell>
                </nut-form>
            </view>
        </view>
        <!-- <basic-map /> -->
    </basic-layout>
</template>
